package sv.com.renacempleo.web.controller.ctg;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import sv.com.renacempleo.dto.ctg.CtgCriteriosVinculacion;
import sv.com.renacempleo.exception.WebException;
import sv.com.renacempleo.web.controller.BaseController;
import sv.com.renacempleo.web.util.DBContext;
import sv.com.renacempleo.web.util.WebUtilidades;

@SuppressWarnings("serial")
@Controller
@RequestMapping("/admin/vinculacion")
public class CtgCriterioVinculacionController extends BaseController{

	@RequestMapping(value = "view", method = {RequestMethod.POST})
	public String view(ModelMap model, 
			@RequestParam (required = false) String header){
		model.addAttribute(WebUtilidades.HEADER_TITLE, StringUtils.isBlank(header) ? "CRITERIOS DE VINCULACION" : header);
		try {
			model.put("data", JSONArray.fromObject(DBContext.getCtgCriteriosVinculacionDao().findAllActivesAsArray()));
		} catch (Exception e) {
			logger.error("view", e);
		}
		return "admin/catalogo/ctgCriterioVinculacion";
	}
	
	@RequestMapping(value = "guardar", method = {RequestMethod.POST})
	public void guardar(
			@ModelAttribute CtgCriteriosVinculacion ctgCriteriosVinculacion,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			DBContext.getCtgCriteriosVinculacionDao().save(ctgCriteriosVinculacion);
			result.put("data", JSONArray.fromObject(DBContext.getCtgCriteriosVinculacionDao().findAllActivesAsArray()));
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("save", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("save", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		
		serializeObject(result, response);
	}
}
